package com.cy.uv.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;
import java.util.Map;

public class Jwt {
    private final static long TTL = 1000*60*60*24;          //token的过期时间1天。
    private final static String SECRET_KEY = "A/.Sss324hah21asdjlkcxb.rt2-09z.sdfm!~";//密钥。
    public static String createToken(String username, Map<String,Object> claims){
        Date now=new Date();
        JWTCreator.Builder builder = JWT.create();
        String token=builder.withSubject(username)
                .withPayload(claims)
                .withExpiresAt(new Date(now.getTime() + TTL))
                .sign(Algorithm.HMAC256(SECRET_KEY));
        System.out.println(token);
        return token;
    }

    public static Map<String,Claim> getClaims(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        return claims;
    }
}
